export default {
  namespaced: true,
  state: () => ({
    cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
    cartCount: uni.getStorageSync('cartCount') || 0
  }),
  mutations: {
    // 添加购物车
    addCart(state, goods) {
      const findResult = state.cart.find((item) => item.goods_id === goods.goods_id)
      if (!findResult) {
        state.cart.push(goods)
        state.cartCount++
      } else {
          if (findResult.goods_count >= 10) {
            uni.showToast({
              title: '该商品最多购买10件',
              icon: 'none'
            })
            return
          }
          findResult.goods_count++
      }
      this.commit('m_cart/saveToStorage')
    },
    // 修改每个商品选中状态
    changeCartState(state, obj){
      const { goods_id, goods_state } = obj
      const findResult = state.cart.find(item => item.goods_id === goods_id)
      if(findResult){
        findResult.goods_state = goods_state
        this.commit('m_cart/saveToStorage')
      }
    },
    // 修改全部商品选中状态
    changeAllState(state){
      const isAllSelected = this.getters['m_cart/flag']; // 访问 getter
      state.cart.forEach(item => item.goods_state = !isAllSelected);
      this.commit('m_cart/saveToStorage');
    },
    // 修改商品的数量
    changeCount(state, obj){
      const { goods_id, goods_count } = obj
      const findResult = state.cart.find(item => item.goods_id === goods_id)
      if(findResult){
        findResult.goods_count = goods_count
        this.commit('m_cart/saveToStorage')
      }
    },
    // 删除某个商品
    deleteCart(state, goods_id){
      state.cart = state.cart.filter(item => item.goods_id !== goods_id)
      state.cartCount = state.cart.length
      this.commit('m_cart/saveToStorage')
    },
    // 封装一个持久化购物车数据的函数
    saveToStorage(state){
      uni.setStorageSync('cart', JSON.stringify(state.cart))
      uni.setStorageSync('cartCount', state.cartCount)
    }
  },
  getters: {
    // 是否全选状态
    flag(state){
      return state.cart.length > 0 && state.cart.every(item => item.goods_state);
    },
    // 选中的商品
    selectedGoods(state) {
      return state.cart.filter(item => item.goods_state)
    },
    // 选中的商品种类
    selectedSum(state, getters) {
      return getters.selectedGoods.length
    },
    // 合计价格
    selectedPrice(state, getters) {
      return getters.selectedGoods.reduce((sum, item) => sum + item.goods_count * item.goods_price, 0).toFixed(2)
    }
  }
}